package cn.tedu.csmall.product.service.impl;

import cn.tedu.csmall.product.ex.ServiceException;
import cn.tedu.csmall.product.mapper.PictureMapper;
import cn.tedu.csmall.product.pojo.dto.PictureAddNewDTO;
import cn.tedu.csmall.product.pojo.entity.Picture;
import cn.tedu.csmall.product.pojo.vo.PictureStandardVO;
import cn.tedu.csmall.product.service.IPictureService;
import cn.tedu.csmall.product.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class PictureServiceImpl implements IPictureService {
    @Autowired
    private PictureMapper pictureMapper;
    @Override
    public void addNew(PictureAddNewDTO pictureAddNewDTO) {
        log.debug("开始处理【添加图片】的业务,参数: {}",pictureAddNewDTO);
        // 创建Picture对象
        Picture picture = new Picture();
        // 调用BeanUtils.copyProperties(源,目标)将参数对象中的属性复制到Picture对象中
        BeanUtils.copyProperties(pictureAddNewDTO,picture);
        // 调用Mapper对象的insert()执行插入图片数据
        log.debug("插入数据:{}",picture);
        int rows = pictureMapper.insert(picture);
        if (rows != 1){
            String message = "添加图片失败,服务器忙,请稍后再尝试!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_INSERT,message);
        }
    }

    @Override
    public void delete(Long id){
        log.debug("开始处理【根据ID删除图片】的业务,参数: {}",id);
        PictureStandardVO picture = pictureMapper.getStandardById(id);
        log.debug("根据ID={}检查图片数据是否存在,查询结果: {}",id,picture);
        if (picture == null){
            String message = "尝试删除的图片数据不存在";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND,message);
        }
        log.debug("即将执行删除,参数: {}",id);
        int rows = pictureMapper.deleteById(id);
        if (rows != 1){
            String message = "删除图片失败,服务器忙,请稍后再尝试!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_DELETE,message);
        }
    }


}
